# -*- coding: utf-8 -*-

from server.entity.user import User
from server.database.mydb import MyDB


class UserService(object):

    def __init__(self, file = "database/user.db"):
        self.db = MyDB(file)

    def queryUserByUsername(self, username):
        """通过用户名查询用户"""
        sql = r"select username, win, lose, tie, score from user where username = ?"
        result = self.db.queryone(sql, username)
        if not result:
            return
        user = User(result[0], result[1], result[2], result[3], result[4])
        return user

    def queryAllUser(self):
        """查询所有用户"""
        sql = r"select username, win, lose, tie, score from user"
        result = self.db.queryall(sql)
        users = []
        for r in result:
            user = User(r[0], r[1], r[2], r[3], r[4])
            users.append(user)
        return users

    def userExists(self, username):
        """判断用户是否存在"""
        if self.queryUserByUsername(username) is None:
            return False
        else:
            return True

    def insertOrUpdateUser(self, user):
        """保存用户"""
        if self.userExists(user.username):
            sql = r"update user set win = ?, lose = ?, tie = ?, score = ? where username = ?"
            self.db.insert(sql, user.win, user.lose, user.tie, user.score, user.username)
        else:
            sql = r"insert into user(username, win, lose, tie, score) values (?, ?, ?, ?, ?)"
            self.db.insert(sql, user.username, user.win, user.lose, user.tie, user.score)

    def close(self):
        self.db.close()

if __name__ == "__main__":
    userservice = UserService()
    user = userservice.queryUserByUsername('test')
    print user

    list = userservice.queryAllUser()
    for index, user in enumerate(list):
        print index, unicode(user)

    userservice.close()